﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.Navigate;
using G.WeiBo.WebAPI.Domain;
using G.WeiBo.View.ChildWindows;
using G.Controls;
using G.WeiBo.WebAPI.Response;
using G.WeiBo.WebAPI.Request;
using Microsoft.Phone.Shell;
using System.Collections.ObjectModel;

namespace G.WeiBo.View
{
    public partial class CommentsList : GBasePage
    {
        public CommentsList()
        {
            InitializeComponent();
        }
        protected override void OnOrientationChanged(OrientationChangedEventArgs e)
        {
            base.OnOrientationChanged(e);
            switch (e.Orientation)
            {
                case PageOrientation.LandscapeLeft:
                case PageOrientation.LandscapeRight:
                    //scrollViewer_Message.Visibility = System.Windows.Visibility.Collapsed;
                    txtComment.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                case PageOrientation.PortraitUp:
                    //scrollViewer_Message.Visibility = System.Windows.Visibility.Visible;
                    txtComment.Visibility = System.Windows.Visibility.Visible;
                    break;
            }
        }
        Message message;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            message = this.NavigationContext.Param as Message;
            messageControl.Message = message;
            GlobalStaticData.Client.Execute(new GetMessageCmtCountsRequest { IDs = message.Id }, (c) =>
            {
                if (!c.IsError)
                {
                    message.Count = c.Response.FirstOrDefault();
                }
            });
        }

        private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;
            BrowserBigImageChildWindow childWindow = new BrowserBigImageChildWindow();
            childWindow.IsOpen = true;
            childWindow.Url = new Uri(img.Tag as string, UriKind.RelativeOrAbsolute);
            e.Handled = true;
        }

        FrameworkElement tempStackPanel;
        private void listBoxComments_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listBoxComments.SelectedItem != null)
            {
                if (tempStackPanel != null)
                    tempStackPanel.Visibility = System.Windows.Visibility.Collapsed;
                ListBoxItem listBoxItem = listBoxComments.ItemContainerGenerator.ContainerFromItem(listBoxComments.SelectedItem) as ListBoxItem;
                if (listBoxItem != null)
                {
                    var list = listBoxItem.GetVisualDescendants<StackPanel>();
                    foreach (var item in list)
                    {
                        if (item.Name == "stackPanelReply")
                        {
                            tempStackPanel = item;
                            item.Visibility = System.Windows.Visibility.Visible;
                            break;
                        }
                    }

                }
                listBoxComments.SelectedItem = null;
            }


        }

        private void listBoxComments_BeginLoadData(object sender, PageEventArgs e)
        {
            ObservableCollection<Comment> itemsSource = this.listBoxComments.ItemsSource as ObservableCollection<Comment>;
            Int64 id = 0;
            if (itemsSource != null && itemsSource.Count > 0)
                id = itemsSource.First().Id;
            GlobalStaticData.Client.Execute(new GetCommentsRequest { MessageID = message.Id, Count = e.PageSize, Page = e.PageNum, Max_Id = id }, (c) =>
            {
                listBoxComments.LoadData<Comment>(c.Comments);
                if (c.Comments == null || c.Comments.Length < listBoxComments.PageSize)
                {
                    listBoxComments.CancelPageListBox();
                }
            });

        }

        private void btnZhuanfa_Click(object sender, EventArgs e)
        {
            //ApplicationBarIconButton btn = this.ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            //btn.IsEnabled = false;
            //GetAPIData.RepostStatues(RepostStatuesComplete, message.Id, null, false);

        }
        private void RepostStatuesComplete(Message msg)
        {
            ApplicationBarIconButton btn = this.ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            btn.IsEnabled = false;
            this.ShowState("转发成功");
            btn.IsEnabled = true;
        }

        private void headImg_Click(object sender, RoutedEventArgs e)
        {
            ImageButton btn = sender as ImageButton;
            Comment cmt = btn.DataContext as Comment;
            NavigationService.Navigate("/View/UserInfoPage.xaml", cmt.User);
        }

        private void btnNickName_Click(object sender, RoutedEventArgs e)
        {

            TextButton btn = sender as TextButton;
            Comment cmt = btn.DataContext as Comment;
            NavigationService.Navigate("/View/UserInfoPage.xaml", cmt.User);
        }

        private void btnComment_Click(object sender, EventArgs e)
        {
            if (txtComment.Text == string.Empty)
            {
                this.ShowState("请填写评论内容", new SolidColorBrush(Colors.Red));
                return;
            }
            this.Focus();
            GlobalStaticData.Client.Execute(new CommentRequest { ID = message.Id, Comment = this.txtComment.Text }, (c) =>
            {
                if (!c.IsError && c.Response != null)
                {
                    this.ShowState("评论成功！");
                    this.txtComment.Text = string.Empty;
                    this.listBoxComments.InsertOf<Comment>(c.Response, 0);
                }
            });

        }
        private void txtReply_KeyUp(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                this.Focus();
                TextBox t = sender as TextBox;
                if (!string.IsNullOrEmpty(t.Text))
                {
                    Comment cmt = t.DataContext as Comment;
                    GlobalStaticData.Client.Execute(new ReplyCommentRequest { ID = this.message.Id, CId = cmt.Id.ToString(), Comment = t.Text }, (c) =>
                    {
                        if (!c.IsError && c.Response != null)
                        {
                            this.ShowState("评论成功！");
                            this.txtComment.Text = string.Empty;
                            this.listBoxComments.InsertOf<Comment>(c.Response, 0);
                            tempStackPanel.Visibility = System.Windows.Visibility.Collapsed;
                        }
                    });
                }

            }
        }
        bool isShow = false;
        private void btnShowWeibo_Click(object sender, EventArgs e)
        {
            AnimateMessage();
        }

        private void AnimateMessage()
        {
            //if (isShow)
            //{
            //    Storyboard storybord = this.Resources["close"] as Storyboard;
            //    (storybord.Children[0] as DoubleAnimation).To = -this.messageBorder.ActualHeight;
            //    storybord.Begin();
            //    isShow = false;
            //}
            //else
            //{
            //    (this.Resources["open"] as Storyboard).Begin();
            //    isShow = true;
            //}
        }

        private void NormalButton_Click(object sender, RoutedEventArgs e)
        {
            AnimateMessage();
        }
        ContextMenu contextMenu;
        private void messageContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            contextMenu.Items.Clear();
            MenuItem menuItem;
            MenuData menuData;
            this.TextTopics.ForEach((s) =>
            {
                menuData = new MenuData(MenuItemType.Topic, s);
                menuItem = new MenuItem { Header = "进入话题：" + s, Tag = menuData };
                menuItem.Click += new RoutedEventHandler(menuItem_Click);
                contextMenu.Items.Add(menuItem);
            });

            //if (this.MessageChildControl != null)
            //{
            //    this.MessageChildControl.GetTextTopics().ForEach((s) =>
            //    {
            //        menuData = new MenuData(MenuItemType.Topic, s);
            //        menuItem = new MenuItem { Header = "进入话题：" + s, Tag = menuData };
            //        menuItem.Click += new RoutedEventHandler(menuItem_Click);
            //        contextMenu.Items.Add(menuItem);
            //    });
            //}
            this.TextUrls.ForEach((s) =>
            {
                menuData = new MenuData(MenuItemType.Url, s);
                menuItem = new MenuItem { Header = "打开网址：" + s, Tag = menuData };
                menuItem.Click += new RoutedEventHandler(menuItem_Click);
                contextMenu.Items.Add(menuItem);
            });

            //if (this.MessageChildControl != null)
            //{
            //    this.MessageChildControl.GetTextUrls().ForEach((s) =>
            //    {
            //        menuData = new MenuData(MenuItemType.Url, s);
            //        menuItem = new MenuItem { Header = "打开网址：" + s, Tag = menuData };
            //        menuItem.Click += new RoutedEventHandler(menuItem_Click);
            //        contextMenu.Items.Add(menuItem);
            //    });
            //}
            if (contextMenu.Items.Count == 0)
            {
                contextMenu.IsOpen = false;
            }
        }

        void menuItem_Click(object sender, RoutedEventArgs e)
        {
            //MenuItem menuItem = sender as MenuItem;
            //MenuData data = menuItem.Tag as MenuData;
            //if (data != null)
            //{
            //    switch (data.Type)
            //    {
            //        case MenuItemType.Topic:
            //            NavigationService.Navigate("/View/TopicBrowser.xaml?topicName=" + data.Data, null);
            //            break;
            //        case MenuItemType.Url:
            //            BrowserWebChildWindow child = new BrowserWebChildWindow();
            //            child.Url = new Uri(data.Data, UriKind.Absolute);
            //            child.Show();
            //            break;
            //        default:
            //            break;
            //    }
            //}
        }

        //private void btnText_Click(object sender, RoutedEventArgs e)
        //{
        //    FormatTextButton btn = sender as FormatTextButton;
        //    this.TextTopics = btn.Topics;
        //    this.TextUrls = btn.Urls;
        //    if (contextMenu != null)
        //    {
        //        contextMenu.IsOpen = true;
        //    }
        //}

        private List<string> TextUrls;


        private List<string> TextTopics;


        public class MenuData
        {
            public MenuData(MenuItemType type, string data)
            {
                this.Type = type;
                this.Data = data;
            }
            public MenuItemType Type { get; private set; }
            public string Data { get; private set; }
        }
        public enum MenuItemType
        {
            Url,
            Topic
        }

        private void messageContextMenu_Loaded(object sender, RoutedEventArgs e)
        {
            this.contextMenu = sender as ContextMenu;
        }

        private void btnReply_Click(object sender, RoutedEventArgs e)
        {

            //UIElement btn = sender as UIElement;
            //var parent = btn.GetParent(2) as StackPanel;
            //TextBox textBox = parent.FindName("txtReply") as TextBox;
            //if (textBox != null)
            //{
            //    if (textBox.Text == string.Empty)
            //    {
            //        this.ShowState("请输入回复内容！", new SolidColorBrush(Colors.Red));
            //        return;
            //    }
            //    Comment cmt = parent.DataContext as Comment;
            //    GetAPIData.ReplyComment((data) =>
            //    {
            //        if (data != null)
            //        {
            //            this.Dispatcher.BeginInvoke(() =>
            //            {
            //                ObservableCollection<Comment> comments = this.listBoxComments.ItemsSource as ObservableCollection<Comment>;
            //                comments.Insert(0, data);
            //                textBox.Text = string.Empty;
            //                this.ShowState("回复成功！");
            //            });
            //        }
            //    }, cmt.Id, textBox.Text, this.message.Id);
            //}
            //StackPanel stackPanel = btn.GetParent();
        }

        private void btnAddFavior_Click(object sender, EventArgs e)
        {
            //ApplicationBarIconButton btn = sender as ApplicationBarIconButton;
            //btn.IsEnabled = false;
            //GetAPIData.CreateFavorites((data) =>
            //{

            //    this.Dispatcher.BeginInvoke(() =>
            //    {
            //        if (data != null)
            //        {
            //            this.ShowState("收藏成功！");
            //        }
            //        btn.IsEnabled = true;
            //    });

            //}, this.message.Id);
        }

        private void messageControl_Loaded(object sender, RoutedEventArgs e)
        {
            isShow = true;
            AnimateMessage();
        }


        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.listBoxComments.ClearItems();
            this.listBoxComments.EnableTombstoneListBox<Comment>(this);
        }

        private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (panorama.SelectedIndex == 1 && listBoxComments.ItemsSource == null && !listBoxComments.IsEnablePageListBox)
            {
                this.listBoxComments.EnableTombstoneListBox<Comment>(this);
            }
        }

        private void btnFoward_Click(object sender, EventArgs e)
        {
            Command.ForwardCommand f = new Command.ForwardCommand();
            f.Execute(this.message);
        }


    }
}